<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <Search :allOpts="formInline.allOpts" v-model="formInline.cOpts" @blur="search"></Search>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleAdd">创建</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <el-table
      :data="tableData"
      border
      style="width: 100%"
      @row-click="handleRowClick">
      <el-table-column type="expand">
        <template scope="props">
          <Page6311 :model="props.row"></Page6311>
        </template>
      </el-table-column>
      <!--<el-table-column type="selection" width="55"></el-table-column>-->
      <el-table-column prop="name_space" label="命名空间"></el-table-column>
      <el-table-column prop="table_name" label="表名"></el-table-column>
      <el-table-column label="操作" width="250">
        <template scope="scope">
          <el-button :type="scope.row.enable=='1'?'info':'warning'" size="small" @click='handleCGTBStatus(scope)'>
            {{scope.row.enable | isEnabled}}
          </el-button>
          <el-button type="danger" size="small" @click="handleDel(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- <el-col style="text-align: center;padding: 20px 0 0 0;">
         <el-button type="text" @click="pushRoms">加载更多</el-button>
     </el-col>-->

    <!--分页-->
    <!--<el-col :span="24" class="toolbar" style="padding-bottom:10px;">
        <el-pagination @size-change="sizeChange" :current-page="1" :page-sizes="[5, 10, 20, 50]" :page-size="20"
                       layout="total, sizes, prev, pager, next, jumper" :total="400"
                       style="float:right"></el-pagination>
    </el-col>-->
    <!--编辑界面-->
    <el-dialog :title="formTitle" v-model="dialogFormVisible" size="tiny" @close="resetForm">
      <el-form :model="form" :rules="editFormRules" ref="form" :label-width="formLabelWidth">
        <!--选择-->
        <el-form-item label="命名空间" prop="name_space">
          <el-select v-model="form.name_space" placeholder="请选择"
                     @change=""
                     style="width: 100%;">
            <el-option v-for="o in name_space_opt" :label="o.label" :value="o.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="表名" prop="table_name">
          <el-input v-model="form.table_name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="预分区" prop="split_keys">
          <Attrinput v-model="form.split_keys" type="2"></Attrinput>
        </el-form-item>

        <el-form-item label="列簇" prop="familis">
          <Columns v-model="form.familis" type="1"></Columns>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="resetForm">取 消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">{{btnEditText}}</el-button>
      </div>
    </el-dialog>

  </section>
</template>
<script>
  //	import util from '../../common/util'
  import Search from '../../components/Search.vue'
  import Attrinput from '../../components/Attrinput.vue'
  import Columns from '../../components/Columns.vue'
  import Page6311 from './Page6311.vue'
  import dao from '../../common/dao'
  import util from '../../common/util'
  export default {
    components: {Search, Page6311, Columns, Attrinput},
    data() {
      return {
        activeName: 'first',
        name_space_opt: [],
        formInline: {
          allOpts: [{
            key: 'name_space',
            label: '命名空间',
            type: 'sel',
            selOption: [],
            val: ''
          }, {
            key: 'table_name',
            label: '表名',
            type: '',
            val: ''
          }],
          cOpts: [{
            key: 'name_space',
            label: '命名空间',
            type: 'sel',
            selOption: [],
            val: ''
          }, {
            key: 'table_name',
            label: '表名',
            type: '',
            val: ''
          }]
        },
        formLabelWidth: '120px',
        editFormRules: {
          name_space: [
            {required: true, message: '请选择命名空间', trigger: 'change'}
          ],
          table_name: [
            {required: true, message: '输入表名', trigger: 'blur'},
            {validator: util.validateString, trigger: 'blur'}
          ],
          /* split_keys: [
           {type: 'array', required: true, message: '输入预分区', trigger: 'change'}
           ],*/
          familis: [
            {type: 'array', required: true, message: '输入列簇！', trigger: 'change'},
            {
              validator: (rule, value, callback) => {

                this.form.familis.map((item, index) => {
                  if (item.column_name == '') {
                    callback(new Error(`请输入列簇 ${index+1} column_name！`))
                    return false
                  } else {
                    item.attributes.map((k, i) => {
                      if (k.key == '') {
                        callback(new Error(`请输入列簇${index+1},第${i+1}行key值!`))
                        return false
                      } else if (k.val == '') {
                        callback(new Error(`请输入列簇${index+1},第${i+1}行val值!`))
                        return false
                      }/*else {
                        callback()
                      }*/
                    })
                  }
                })
                callback()
              }, trigger: 'blur'
            }
          ],
        },
        butStatus: {
          selectNum: true,
          homeTitle: {},
          homeData: [],
        },
        tableData: [],
        formTitle: '创建新表',
        dialogFormVisible: false,
        btnEditText: '保存',
        form: {
          name_space: '',
          split_keys: [{key: '', val: ''}],
          familis: [{
            column_name: '',
            attributes: [{key: '', val: ''}],
          }],
        },
      }
    },
    methods: {
      pushRoms () { },
      search (val) {
        //调用查询服务
        this.getHomeData();
      },
      pageInit(){
        dao.listNameSpace({}).then(res => {
          if (!res.body || res.body.retCode != '200') {
            util.apiMsg(res);
            return false;
          }
          let arr = [];
          let results = res.body.results || [];
          results.map(item => {
            let obj = {
              label: item,
              value: item,
            };
            arr.push(obj);
          });
          this.formInline.allOpts[0].selOption = arr;
          this.formInline.cOpts[0].selOption = arr;
          this.name_space_opt = arr;
        });
      },
      getHomeData () {
        //name_space 命名空间
        //table_name
        //
        let obj = {};
        this.formInline.cOpts.map(item => {
          obj[item.key] = item.val;
        });
        dao.listTables(obj).then(res => {
          if (!res.body || res.body.retCode != '200') {
            util.apiMsg(res);
            return false;
          }

          this.tableData = res.body.results || [];
        });
      },
      tabHandleClick(tab, event) {
      },
      handleRowClick(row, event, column){
      },
      handleAdd(){
        this.form= {
          name_space: '',
            split_keys: [{key: '', val: ''}],
            familis: [{
            column_name: '',
            attributes: [{key: '', val: ''}],
          }],
        },
        this.dialogFormVisible = true;
      },
      handleSelectionChange (val) {
        (val.length == 1) ? this.butStatus.selectNum = false : this.butStatus.selectNum = true
      },
      sizeChange () { },
      form2req(obj){
        let split_keys = [];
        this.form.split_keys.map(sk => {
          if (sk.val != "") {
            split_keys.push(sk.val);
          }
        });
        obj.split_keys = split_keys;
      },
      editSubmit () {

        this.$refs.form.validate((valid) => {
          if (!valid) return false;
          this.$confirm('此操作将创建表, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {


             let obj = JSON.parse(JSON.stringify(this.form));
            obj.familis.map(row => {
              let attributes = {column_name: row.ccolumn_name};
              row.attributes.map(col => {
                attributes[col.key] = col.val;
              });
              row.attributes = attributes;
            });
            this.form2req(obj);

            this.btnEditText = '保存中';
            this.editLoading = true;
            dao.tableCreate(obj).then(res => {
              this.btnEditText = '保存';
              this.editLoading = false;
              if (!res.body || res.body.retCode != '200') {
                util.apiMsg(res);
                return false;
              }
              this.$message({
                type: 'success',
                message: '创建成功!'
              });
              this.dialogFormVisible = false;
              this.getHomeData();
            }).catch(res => {
              this.btnEditText = '保存';
              this.editLoading = false;
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消创建'
            });
          });
        })
      },
      handleCGTBStatus(scope){
        let enable = scope.row.enable;
        let act = "启动";
        let fun = 'enable';
        if (enable == '1') {
          act = "禁用";
          fun = 'disable';
        } else if (enable == '0') {
        } else {
          this.$message({
            type: 'info',
            message: '参数有误'
          });
          return false;
        }
        //提示
        this.$confirm(`此操作将${act}表, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(() => {
          let name_space = scope.row.name_space;
          let table_name = scope.row.table_name;
          dao[fun]({name_space, table_name}).then(res => {
            if (!res.body || res.body.retCode != '200') {
              util.apiMsg(res);
              return false;
            }
            this.$message({
              type: 'info',
              message: '操作成功'
            });
            this.getHomeData();
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      },
      handleDel(scope){
        let enable = scope.row.enable;
        if (enable != '0') {
          this.$message({
            type: 'warning',
            message: '不能删除可用状态的表！'
          });
          return false;
        }
        //提示
        this.$confirm(`此操作将删除表, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(() => {
          let name_space = scope.row.name_space;
          let table_name = scope.row.table_name;
          dao.dropTable({name_space, table_name}).then(res => {
            if (!res.body || res.body.retCode != '200') {
              util.apiMsg(res);
              return false;
            }
            this.$message({
              type: 'info',
              message: '删除成功'
            });
            this.getHomeData()
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      resetForm () { //重置表单
        this.dialogFormVisible = false
      }
    },
    mounted () {
      this.pageInit();
      this.getHomeData();
    }
  }
</script>
<style scoped>

</style>
